// popup <==> background
document.getElementById('jumpToScm').addEventListener("click", function() {
   chrome.tabs.create({ url: 'http://scm.zhr08.com/gdpaas/login/index.htm' });
//    chrome.tabs.create({ url: 'http://qzzhr.puc123.cn/gdpaas/login/index.htm' });
});

document.addEventListener('DOMContentLoaded', function() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        var currentTab = tabs[0];
        var currentTabUrl = currentTab.url;
        // 检查当前页面的 URL 是否符合指定条件
        if (currentTabUrl.includes('item.taobao.com/item.htm') || currentTabUrl.includes('detail.tmall.com/item.htm') || currentTabUrl.includes('detail.vip.com/detail')
        || currentTabUrl.includes('item.jd.com')) {
            // 当前页面是在 'example.com' 下，显示popup内容
            document.getElementById('getinfo').addEventListener('click', getInfoBtn);
            document.getElementById('btn-submit').addEventListener("click", postData);
        } else {
            // 当前页面不符合条件，显示提示信息或禁用功能
            document.getElementById('getinfo').removeEventListener('click', getInfoBtn);
            document.getElementById('btn-submit').removeEventListener("click", postData);
        }
    });
});

function postData(event) {
    event.preventDefault();
    const formElement = document.getElementById('mainform'); // 通过表单的 ID 获取表单元素
    // 使用FormData对象来获取表单的数据
    const formData = new FormData(formElement);
    // 将FormData对象转换为对象字面量
    const formDataObject = {};
    formData.forEach(function(value, key){
        formDataObject[key] = value;
    });
    formDataObject["EDIT_TYPE"] = "ADD";    //处理方式为新增
    formDataObject["base"] = formDataObject["base"].replaceAll("\r\n", "\n").replaceAll("\n","#0D0A")
    // 输出JSON字符串
    $.ajax({    
        url: properties.postURL,   //发起接口调用
        method: 'POST',
        contentType: 'application/x-www-form-urlencoded',
        data: formDataObject,
        success: function(response) {
            // 请求成功时的处理
            console.log(response);
            const {code, msg} = JSON.parse(response);
            if(code == 500) {
                alert(msg, 'error');
            } else {
                alert('Nice, you triggered this alert message!', 'success')
            }
        },
        error: function(xhr, status, error) {
            // 请求出错时的处理
            console.log(error);
        }
    });
}

function getInfoBtn(event) {
    event.preventDefault();
    /**
     * 获取采样人信息，需要求提前登陆数据中台系统
     */
    chrome.tabs.query({title: properties.name, url: properties.mainPage}, function(scmTabs) {
        //通讯，通知content获取详细信息，并在popup界面中展示信息
        if(scmTabs.length > 0) {
            chrome.storage.session.get(["uname", "uid"], function(result) {
                document.getElementById('item_user').value = result.uname || '';
                console.log("Retrieved data: " + result.uname);
            });
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                let tabId = tabs[0].id;
                //获取链接地址
                const url  = tabs[0].url;
                document.getElementById('item_link').value = url;  
                /**
                 * 识别平台
                 */
                var platform = (url.indexOf("detail.tmall.com") > -1 || url.indexOf("item.taobao.com") > -1) ? "淘宝" : 
                               url.indexOf("detail.vip.com") > -1 ? "唯品会" : url.indexOf("item.jd.com") > -1 ? "京东" : "";
                chrome.tabs.sendMessage(tabId, {"platform": platform,"action": "getInfo"}, function(response) {
                    if (response) {
                        var content = response.response;
                        //设置表单内容
                        document.getElementById('item_name').value = content.title  || '';
                        document.getElementById('item_style').value = content.style  || '';
                        document.getElementById('item_shop').value = content.shop  || '';
                        document.getElementById('item_saleYear').value = content.year  || '';
                        document.getElementById('item_saleDesc').value = content.saleDesc || '';
                        document.getElementById('item_seasonDesc').value = content.season  || '';
                        document.getElementById('item_price').value = content.price  || '';
                        document.getElementById('item_searchTime').value = new Date().toLocaleString();
                        document.getElementById('item_base').value = content.base.join('\r\n');
                        document.getElementById('item_platform').value = platform;
                        // 加载图片资源
                        (async () => {
                            try {
                                var picURL = content.picture;
                                if(picURL) {
                                    document.getElementById('item_pic_url').value = picURL;
                                    const base64Data = await convertImageToBase64(picURL);
                                    document.getElementById('item_pic').src = base64Data;
                                }
                            } catch (error) {
                            }
                        })();
                    } else {
                        console.log('Failed to receive response from content script');
                    }
                })
            });
        } else {
            $('#myModal').modal('show');
        }
    })
}

async function convertImageToBase64(url) {
    const response = await fetch(url);
    const blob = await response.blob();

    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        
        reader.onload = () => {
            const base64data = reader.result;
            resolve(base64data);
        };
        reader.onerror = reject;
        reader.readAsDataURL(blob);
    });
}
